type CacheType = "localStorage" | "sessionStorage"
import { CacheKeyEnum } from '@/constants/cacheKey';
import { Encrypt, Decrypt } from '../utils/crypto';

interface CacheOptions {
  /** 是否加密存储，默认为false */
  encrypt?: boolean;
  /** 是否自动序列化对象，默认为true */
  autoSerialize?: boolean;
}

interface Cache {
  /**
   * 存储值到缓存
   * @param key 缓存键
   * @param value 缓存值（可以是字符串、数字、对象、数组等）
   * @param options 缓存选项
   */
  set: <T = any>(key: string, value: T, options?: CacheOptions) => void;
  
  /**
   * 从缓存获取值
   * @param key 缓存键
   * @param options 缓存选项
   * @returns 缓存值，如果不存在则返回null
   */
  get: <T = any>(key: string, options?: CacheOptions) => T | null;
  
  /**
   * 删除指定键的缓存
   * @param key 缓存键
   */
  remove: (key: string) => void;
  
  /**
   * 清除所有缓存
   */
  clear: () => void;
  
  /**
   * 获取所有缓存键列表
   */
  getAllKeys: () => string[];
}

/**
 * 默认需要加密的键列表
 */
const ENCRYPT_KEYS = [
  CacheKeyEnum.USER,
  CacheKeyEnum.TOKEN_KEY,
  CacheKeyEnum.REFRESH_TOKEN_KEY
];

/**
 * 检查是否为需要加密的键
 */
const isEncryptKey = (key: string): boolean => {
  return ENCRYPT_KEYS.includes(key as CacheKeyEnum);
};

/**
 * 智能缓存Hook
 * 自动处理对象序列化、加密解密
 */
export default function useCache(cacheType: CacheType = "localStorage"): Cache {
  const cache = cacheType === "sessionStorage" ? sessionStorage : localStorage;
  console.log("缓存类型:", cacheType);
  
  // 验证键的有效性
  const isValidKey = (key: string): boolean => {
    return typeof key === 'string' && key.trim() !== '';
  };
  /**
   * 存储值到缓存
   */
  const set = <T = any>(key: string, value: T, options: CacheOptions = {}): void => {
    if (!isValidKey(key) || value == null) {
      return;
    }
    
    const {
      encrypt = isEncryptKey(key), // 默认根据键名决定是否加密
      autoSerialize = true // 默认自动序列化
    } = options;
    try {
      let valueToStore: string;
      
      if (autoSerialize && (typeof value === 'object' || Array.isArray(value))) {
        // 自动序列化对象和数组
        valueToStore = JSON.stringify(value);
      } else {
        // 基本类型直接转换为字符串
        valueToStore = String(value);
      }
      
      // 如果需要加密，对值进行加密
      if (encrypt) {
        valueToStore = Encrypt(valueToStore);
      }
      cache.setItem(key, valueToStore);
      console.log("存储后立即读取验证:", key, cache.getItem(key));
    } catch (error) {
      console.error(`Failed to set cache for key "${key}":`, error);
    }
  };
  
  /**
   * 从缓存获取值
   */
  const get = <T = any>(key: string, options: CacheOptions = {}): T | null => {
    if (!isValidKey(key)) {
      return null;
    }
    const {
      encrypt = isEncryptKey(key), // 默认根据键名决定是否解密
      autoSerialize = true // 默认自动反序列化
    } = options;
    
    try {
      const item = cache.getItem(key);
      
      if (!item) {
        return null;
      }
      
      let parsedValue: string = item;
      
      // 如果需要解密，对值进行解密
      if (encrypt) {
        try {
          parsedValue = Decrypt(item);
        } catch (decryptError) {
          console.warn(`Failed to decrypt cache for key "${key}", treating as plain text:`, decryptError);
        }
      }
      
      // 如果启用了自动序列化，尝试解析JSON
      if (autoSerialize) {
        try {
           console.log("自动反序列化对象和数组:", JSON.parse(parsedValue));
          return JSON.parse(parsedValue) as T;
         
        } catch (parseError) {
          // 如果解析失败，返回原始字符串值
          return parsedValue as unknown as T;
        }
      }
      
      return parsedValue as unknown as T;
    } catch (error) {
      console.error(`Failed to get cache for key "${key}":`, error);
      // 清除无效的缓存数据
      // remove(key);
      return null;
    }
  };
  
  /**
   * 删除指定键的缓存
   */
  const remove = (key: string): void => {
    if (!isValidKey(key)) {
      return;
    }
    
    try {
      cache.removeItem(key);
    } catch (error) {
      console.error(`Failed to remove cache for key "${key}":`, error);
    }
  };
  
  /**
   * 清除所有缓存
   */
  const clear = (): void => {
    try {
      cache.clear();
    } catch (error) {
      console.error('Failed to clear cache:', error);
    }
  };
  
  /**
   * 获取所有缓存键列表
   */
  const getAllKeys = (): string[] => {
    try {
      const keys: string[] = [];
      for (let i = 0; i < cache.length; i++) {
        const key = cache.key(i);
        if (key) {
          keys.push(key);
        }
      }
      return keys;
    } catch (error) {
      console.error('Failed to get all cache keys:', error);
      return [];
    }
  };
  
  return { set, get, remove, clear, getAllKeys };
}

/**
 * 向后兼容的旧API
 */
export const createCache = useCache;

